package com.pay.ioopos;

import android.util.Log;

import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.X509TrustManager;

import okhttp3.ConnectionSpec;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
	private static final String TAG = HttpUtil.class.getSimpleName();
	private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

	public static String post(String url, String postBody) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG,"请求地址：" + url);
			Log.d(TAG,"请求内容：" + postBody);
		}

		RequestBody body = RequestBody.create(postBody, JSON);
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				.build();
		return execute(request);
	}

	public static String get(String url) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG,"请求地址：" + url);
		}

		Request request = new Request.Builder()
				.url(url)
				.get()
				.build();
		return execute(request);
	}

	public static Response getResponse(String serverUrl) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG,"请求地址：" + serverUrl);
		}

		OkHttpClient client = new OkHttpClient.Builder()
				.connectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT, ConnectionSpec.COMPATIBLE_TLS))
				.sslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory(), trustX509Manager())
				.build();

		Request request = new Request.Builder()
				.url(serverUrl)
				.get()
				.build();
		return client.newCall(request).execute();
	}

	private static String execute(Request request) throws Exception {
		OkHttpClient client = new OkHttpClient.Builder()
				.connectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT, ConnectionSpec.COMPATIBLE_TLS))
				.sslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory(), trustX509Manager())
				.callTimeout(20, TimeUnit.SECONDS)
				.connectTimeout(10, TimeUnit.SECONDS)
				.build();
		String resBody;
		try (Response response = client.newCall(request).execute()) {
			if (Log.isLoggable(TAG, Log.DEBUG)) {
				Log.d(TAG,"远程接口返回状态：" + response.code());
			}
			resBody = response.body().string();
			if (Log.isLoggable(TAG, Log.DEBUG)) {
				Log.d(TAG,"响应内容：" + resBody);
			}
		}
		return resBody;
	}

	private static X509TrustManager trustX509Manager() {
		return new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[]{};
			}
		};
	}

}
